#
# Create directories config/hosts and config/users
# 
# Insert line: [require 'plugins/config_hu_extension/lib/config_hu_extension']
# before Initializer.run in conf/environment.rb file

require "fileutils"

%w(hosts users).each do |dir|
  abs_dir = File.join(File.dirname(__FILE__), "../../../config/#{dir}")
  FileUtils.mkdir abs_dir unless File.exists?(abs_dir)
end

file = File.join(File.dirname(__FILE__), '../../../config/environment.rb')
unless File.exists?(file)
  STDERR.puts("ERROR: Could not locate config/environment.rb file.") 
  exit(1)
end

# 'Modifying a File in Place Without a Temporary File'
# Borrowed from the app_config plugin install.rb.
output= ""
inserted = false
LINE_TO_INSERT = %Q{require 'plugins/config_hu_extension/lib/config_hu_extension'}
File.open(file, 'r+') do |f|   # open file for update
  # read into array of lines and iterate through lines
  f.readlines.each do |line| 
    unless inserted 
      if line.gsub(/#.*/, '').include?(LINE_TO_INSERT)
        inserted = true
      elsif line.gsub(/#.*/, '').include?('Rails::Initializer.run')
        output << LINE_TO_INSERT
        output << "\n"
        inserted = true
      end
    end     
    output << line
  end
  f.pos = 0                     # back to start
  f.print output                # write out modified lines
  f.truncate(f.pos)             # truncate to new length
end   

unless inserted
  STDERR.puts <<END 
ERROR: Could not update config/environment.rb
To finish installation try to add the following line to 
config/environment.rb manually: 
\t#{LINE_TO_INSERT}
NOTE: line must be inserted before Rails::Initializer.run()
END
  exit(1)
end
